package com.springsource.mvc.HandlerMappingAndHandlerAdapter;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;

public class YmlReturnValueHandler implements HandlerMethodReturnValueHandler {
    // 判断是否支持当前方法的返回值，如果返回真，才会调用handleReturnValue方法
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        Yml methodAnnotation = returnType.getMethodAnnotation(Yml.class);
        return methodAnnotation != null;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        // returnValue是方法返回值

        // 将结果写入response中
        HttpServletResponse nativeResponse = webRequest.getNativeResponse(HttpServletResponse.class);
        nativeResponse.setContentType("text/plain;charset=utf-8");
        nativeResponse.getWriter().print("解析了Yml注解:" + returnValue);

        // 告诉SpringMVC请求已处理完毕
        mavContainer.setRequestHandled(true);
    }
}
